import classNames from 'classnames';
import React, { useState, useEffect } from 'react';

interface BackTopProps {
    right?: number
    bottom?: number,
    hiddenValue?: number,
    animationTime?: number,
    children?: React.ReactNode,
    className?: string
}

const BackTop: React.FC<BackTopProps> = (props) => {

    const { right, bottom, animationTime, hiddenValue, children, className } = props;

    const [isShow, setIsShow] = useState<boolean>(false);

    const styles = { right: right + "px", bottom: bottom + "px", display: isShow ? 'block' : 'none' };

    const classed = classNames('yulang-back-top-container', className)
    const backTop = () => {
        let timer: NodeJS.Timer | null;
        timer = setInterval(() => {
            const scrollTop =
                document.body.scrollTop || document.documentElement.scrollTop;
            if (scrollTop === 0) {
                clearInterval(Number(timer));
            }
            document.body.scrollTop = document.documentElement.scrollTop =
                Math.floor(scrollTop * 0.9);
        }, animationTime);
    }

    useEffect(() => {
        if (
            document.documentElement.scrollTop ||
            document.body.scrollTop > (hiddenValue as number)
        ) {
            setIsShow(true)
        } else {
            setIsShow(false)
        }
        window.addEventListener("scroll", () => {
            // 再次滚动时，移除上一次的动画(bug)
            const scrollY =
                document.documentElement.scrollTop || document.body.scrollTop;
            if (scrollY > (hiddenValue as number)) {
                setIsShow(true)
            } else {
                setIsShow(false)
            }
        });
    }, [hiddenValue])

    if (children) {
        return <div className={classed} onClick={backTop} style={styles}>
            {children}
        </div>
    } else {
        return <div className={classed} onClick={backTop} style={styles}>
            回到顶部
        </div>
    }
}

BackTop.defaultProps = {
    right: 0,
    bottom: 0,
    hiddenValue: 0,
    animationTime: 5
}

export default BackTop;